package com.richard.base.view.gdxView.adapter

import android.content.Context
import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.esotericsoftware.spine.*

/**
 ***************************************
 * 项目名称:Giggle
 * @Author wuzhiguo
 * 邮箱：wuzhiguo@ksjgs.com
 * 创建时间: 2020/9/21     3:01 PM
 * 用途:
 *
 *  atlasPath: String,//"spineboy2/spineboy-pma.atlas"
 *  jsonPath: String // "spineboy2/spineboy-ess.json"
 ***************************************
 */
class GdxAdapter(
    context: Context,
    val atlasPath: String,
    val jsonPath: String
) : ApplicationAdapter() {
    lateinit var camera: OrthographicCamera
    lateinit var batch: PolygonSpriteBatch
    lateinit var renderer: SkeletonRenderer
    lateinit var atlas: TextureAtlas
    lateinit var skeleton: Skeleton
    lateinit var state: AnimationState
    lateinit var json: SkeletonJson
    var viewportWidth: Int = 0
    var viewportHeight: Int = 0
    private val context: Context
    override fun create() {
        viewportWidth = Gdx.graphics.width
        viewportHeight = Gdx.graphics.height

        camera = OrthographicCamera(viewportWidth.toFloat(), viewportHeight.toFloat())
        batch = PolygonSpriteBatch()
        renderer = SkeletonRenderer()
        renderer.premultipliedAlpha = true // PMA results in correct blending without outlines.
        atlas = TextureAtlas(Gdx.files.internal(atlasPath))
        //        atlas = new TextureAtlas(Gdx.files.internal("vae/xusong.atlas"));
        json = SkeletonJson(atlas) // This loads skeleton JSON data, which is stateless.
        //scale
        json.scale = viewportWidth.toFloat() / 1920 // Load the skeleton at 60% the size it was in Spine.
        val skeletonData = json.readSkeletonData(Gdx.files.internal(jsonPath))
        //        SkeletonData skeletonData = json.readSkeletonData(Gdx.files.internal("vae/xusong.json"));
        skeleton = Skeleton(skeletonData) // Skeleton holds skeleton state (bone positions, slot attachments, etc).
        //        skeleton.setPosition(DisplayUtil.getDensity_Width(context) / 2, DisplayUtil.getDensity_Height(context) / 3);
        skeleton.setPosition(viewportWidth / 2.toFloat(), 0f)
        val stateData = AnimationStateData(skeletonData) // Defines mixing (crossfading) between animations.
        //        stateData.setMix("run", "jump", 0.2f);
//        stateData.setMix("jump", "run", 0.2f)
        state = AnimationState(stateData) // Holds the animation state for a skeleton (current animation, time, etc).
        //        state.setTimeScale(0.5f); // Slow all animations down to 50% speed.

        // Queue animations on track 0.
//        state.setAnimation(0, "jump", true)
//        state.addAnimation(0, "run", true, 0f) // Run after the jump.

    }

    /**
     * 执行动作
     * @param action String //jump
     */
    fun doAction(action: String, loop: Boolean, listener: ActionCompleteListener) {
        state.setAnimation(0, action, loop)
        state.clearListeners()
        state.addListener(object :AnimationState.AnimationStateListener {
            override fun event(entry: AnimationState.TrackEntry?, event: Event?) {
            }

            override fun start(entry: AnimationState.TrackEntry?) {
            }

            override fun interrupt(entry: AnimationState.TrackEntry?) {
            }

            override fun complete(entry: AnimationState.TrackEntry?) {
                if (!loop) {//非循环的才回调
                    listener.onComplete()
                }
            }

            override fun end(entry: AnimationState.TrackEntry?) {
            }

            override fun dispose(entry: AnimationState.TrackEntry?) {
            }
        })
    }

    /**
     * 监听动画完成回调
     */
    interface ActionCompleteListener {
        fun onComplete()
    }

    override fun render() {
        state.update(Gdx.graphics.deltaTime) // Update the animation time.
        Gdx.gl.glClearColor(0f, 0f, 0f, 0f)
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
        state.apply(skeleton) // Poses skeleton using current animations. This sets the bones' local SRT.
        skeleton.updateWorldTransform() // Uses the bones' local SRT to compute their world SRT.

        // Configure the camera, SpriteBatch, and SkeletonRendererDebug.
        camera.update()
        batch.projectionMatrix.set(camera.combined)
        batch.begin()
        batch.setColor(0f, 0f, 0f, 0f)
        renderer.draw(batch, skeleton) // Draw the skeleton images.
        batch.end()
    }

    override fun resize(width: Int, height: Int) {
        camera.setToOrtho(false)
        //使用scale替代此缩放
//        var newW = width
//        var newH = height
//        val scale = width.toFloat() / camera.viewportWidth
//        newW *= scale.toInt()
//        newH *= scale.toInt()
//        camera.setToOrtho(false, newW.toFloat(), newH.toFloat()) // Update camera with new size.
//        camera.translate((width - newW) / 2.toFloat(), (height - newH) / 2.toFloat())
    }

    override fun dispose() {
        atlas.dispose()
    }

    init {
        this.context = context
    }
}
